//
//  ZFMapManager+layer.swift
//  map
//
//  Created by fyzq on 2024/2/2.
//

import Foundation
import MapboxMaps


private enum ZFMapManagerLayerType  {
    static let terrain_source_id = "terrain_source_id"
    static let terrain_layer_id = "terrain_layer_id"
    
    static let region_layer_id = "region_layer_id"
    static let region_source_id = "region_source_id"
    
}
extension ZFMapManager {
    
    ///切换图层
    func setStyleUrl(url:String){
        mapView!.mapboxMap.styleURI = StyleURI(url: URL(string: url)!)
        
    }
     
}


/**
 地形图
 */
extension ZFMapManager {
    
    ///添加地形图
    func setTerrain(){
        guard let mapView = mapView else {
            return
        }
        var demSource = RasterDemSource(id: ZFMapManagerLayerType.terrain_source_id)
        demSource.url = "mapbox://mapbox.mapbox-terrain-dem-v1"
        demSource.tileSize = 514
        demSource.volatile = true
        do {
            try mapView.mapboxMap.addSource(demSource)
            var terrain = Terrain(sourceId: ZFMapManagerLayerType.terrain_source_id)
            terrain.exaggeration = .constant(Double(1.5))
            try  mapView.mapboxMap.setTerrain(terrain)
        } catch {
            print("setTerrain fail")
        }
        
    }
    
    public func updateExaggeration(value:Float){
        guard let mapView = mapView else {
            return
        }
        do {
           try mapView.mapboxMap.setTerrainProperty("exaggeration", value: value);
        } catch {
            print("updateTerrainLayer fail")
        }
    }
    public func updateVisity(){
        
    }
}



/**
 添加 省份图
 region
 */

extension ZFMapManager {
    
    func setRegionLayer(){
        
        var fillLayer =  FillLayer(id: ZFMapManagerLayerType.region_layer_id, source: ZFMapManagerLayerType.region_source_id)
        fillLayer.fillColor = .constant(StyleColor(R.color.color_455b()!.alpha(0.2)))
        fillLayer.fillOutlineColor = .constant(StyleColor(R.color.color_455b()!.alpha(0.5)))
        var geoSource = GeoJSONSource(id: ZFMapManagerLayerType.region_source_id)
        geoSource.data = nil
        do{
            try mapView?.mapboxMap.addLayer(fillLayer)
            try mapView?.mapboxMap.addSource(geoSource)
        }catch{
            print("setRegionLayer error \(error)")
        }
    }
    
    func updateRegionSource(jsonSource:FeatureCollection){
        guard let mapView = mapView else {
            return
        }
        if !mapView.mapboxMap.sourceExists(withId: ZFMapManagerLayerType.region_source_id){return}
        mapView.mapboxMap.updateGeoJSONSource(withId: ZFMapManagerLayerType.region_source_id, data: .featureCollection(jsonSource))
    }
    
}
